import eventfax.core._

import scala.actors._
import scala.actors.Actor._
import java.io.IOException

abstract class Message
case class StringMessage(val binding: String,var message: String) extends Message

class FooReactor(starterBlock: ReactorCore => Unit) extends ReactorCore(starterBlock) {
  def check_for_actor_messages = {
    Actor.self.receiveWithin(1) {
      case (msg: StringMessage, actor: Actor) => { 
        var t_conn = activeConnections.get(msg.binding)
        t_conn match {
          case Some(conn: Connection) => conn.asInstanceOf[SampleServer].accept_actor_response(msg.message)
          case None => println("Unmatched")
        }
      }
      case msg =>
        msg
    }
  }
}

object UpcaseActor extends Actor {
  def act() {
    loop {
      react {
        case(msg: StringMessage,actor: Actor) => { 
          var new_msg: StringMessage = StringMessage(msg.binding,msg.message.toUpperCase())
          actor ! (new_msg, Actor.self)
        }
      }
    }
  }
}


object SampleServerFactory extends ConnectionFactory {
  def create_connection(): Connection = {
    var sample_server: SampleServer = new SampleServer()
    return sample_server
  }
}

class SampleServer extends Connection { 
  override def post_init() {
    // println(this.bindingStr)
  }

  def receive_data(p_data: FaxData) {
    println(p_data)
    UpcaseActor ! (StringMessage(bindingStr,p_data.toString()), Actor.self)
    send_data(p_data)
  }

  def accept_actor_response(message: String) = {
    send_data(message)
  }
  
  def unbind() {
    println("Client disconnected")
  }
  
  override def connection_completed() {
    println("Connection completed")
  }

  def on_write_error() {
    try {
      close_connection()
      println("Closing damn connection")
    } catch { case ex: IOException => println("error") }
  }

  def say_hello = println("Hello World")
}

object Foo {
  def main(args: Array[String]) {
    UpcaseActor.start()
    new FooReactor(t_reactor => {
      t_reactor.start_server("localhost",9000,SampleServerFactory)
    })
  }
}


